﻿using System;
using System.Collections.Generic;
using System.Linq;
using TZL.Data;

namespace TZL.Web.Data
{
    public class SqlDataHelper
    {
        public List<Config> SelectConfig(string configKey)
        {
            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.Configs
                                 where item.ConfigKey == configKey
                                 select item).OrderByDescending(x => x.ModifyTime).ToList();

                    return query;

                }
            }
            catch (Exception e)
            {
                return null;
            }
        }


        #region News

        public List<News> SelectNews(int categoryId, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.News
                                 where item.CategoryId == categoryId
                                 select item).OrderByDescending(x => x.PublishTime).Skip((pageIndex - 1) * pageSize).Take(pageSize);


                    return query.ToList();

                }
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public int SelectNewsTotalPage(int categoryId, int pageSize = 10)
        {
            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.News
                                 where item.CategoryId == categoryId
                                 select item.NewId).Count();

                    var page = query / pageSize;
                    var p = query % pageSize;
                    if (p > 0)
                    {
                        return page + 1;
                    }
                    return page;
                }
            }
            catch (Exception e)
            {
                return 0;
            }
        }

        public News SelectNewsById(int newsId)
        {
            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.News
                                 where item.NewId == newsId
                                 select item).FirstOrDefault();


                    return query;

                }
            }
            catch (Exception e)
            {
                return null;
            }
        }

        #endregion

        private SqlDataHelper() { }

        private static readonly SqlDataHelper _instance = new SqlDataHelper();

        public static SqlDataHelper Instance
        {
            get { return _instance; }
        }
    }
}